<template>
  <div>
    <div class="request" v-if="!requestAddShow && !orderAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:requestDetail:query']"
          class="btn search"
          @click="getRequestList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:requestDetail:inquiry']"
          class="btn add"
          style="width: 120px"
          @click="handleAddInquiry"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >生成询比价</el-button
        >
        <el-button
          v-hasPermi="['system:requestDetail:purchase']"
          class="btn add"
          style="width: 120px"
          @click="handleAddOrder"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >生成采购订单</el-button
        >
          <!-- v-hasPermi="['system:contractSeal:export1']" -->
        <el-button
          class="btn save"
          @click="handleExport()"
          ><el-icon class="icon" color="#fff"> <Download /> </el-icon
          >导出</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="purchaseApplyCode">请购编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialCode">物料编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialName">物料名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="factoryCode">出厂型号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="technologyParameter">技术参数</el-checkbox>
            </div>
            <div>
              <el-checkbox label="materialUnitName">单位</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchasePrice">单价</el-checkbox>
            </div>
            <div>
              <el-checkbox label="historicalPrice">历史价格</el-checkbox>
            </div>
            <div>
              <el-checkbox label="distributorName">供应商</el-checkbox>
            </div>
            <div>
              <el-checkbox label="manufacturer">生产厂商</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseNumber">请购数量</el-checkbox>
            </div>
            <div>
              <el-checkbox label="stock">库存</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantType">采购类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deliveryDate">期望交付日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectName">关联项目名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDate">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseTrackingStatusName">状态</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item" style="margin-bottom: 10px">
          <el-input
            clearable
            v-model="params.purchaseApplyCode"
            class="search-input"
            placeholder="请输入请购编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.materialCode"
            class="search-input"
            placeholder="请输入物料编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.materialName"
            class="search-input"
            placeholder="请输入物料名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.supplierName"
            class="search-input"
            placeholder="请输入供应商"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.manufactureName"
            class="search-input"
            placeholder="请输入生产厂商"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.nickName"
            class="search-input"
            placeholder="请输入申请人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.projectName"
            class="search-input"
            placeholder="请输入项目名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.applicantType"
            placeholder="请选择采购类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in typeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.purchaseTrackingStatus"
            placeholder="请选择状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in checkOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="requestList"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="checkSelectable"
        />
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="请购编号"
          prop="purchaseApplyCode" v-if="checkList.includes('purchaseApplyCode')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="物料编号"
          prop="materialCode" v-if="checkList.includes('materialCode')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="物料名称"
          prop="materialName" v-if="checkList.includes('materialName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="出厂型号"
          prop="factoryCode" v-if="checkList.includes('factoryCode')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="技术参数"
          prop="technologyParameter" v-if="checkList.includes('technologyParameter')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="单位"
          prop="materialUnitName" v-if="checkList.includes('materialUnitName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="单价"
          prop="purchasePrice" v-if="checkList.includes('purchasePrice')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="历史价格"
          prop="historicalPrice" v-if="checkList.includes('historicalPrice')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="供应商"
          prop="distributorName" v-if="checkList.includes('distributorName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
          >
          <template #default="{ row }">
            <span>{{ row.distributorName ? row.distributorName : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="生产厂商"
          prop="manufacturer" v-if="checkList.includes('manufacturer')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
          >
          <template #default="{ row }">
            <span>{{ row.manufacturer ? row.manufacturer : "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="请购数量"
          prop="purchaseNumber" v-if="checkList.includes('purchaseNumber')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="库存"
          prop="stock" v-if="checkList.includes('stock')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-dropdown v-if="row.stock!=='--'" trigger="hover" @visible-change="handleStock(row)">
              <span class="el-dropdown-link">
                {{ row.stock }}
                <el-icon class="el-icon--right"><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <div class="stock-list">
                      <span class="stock-item">请购编号</span>
                      <span class="stock-item">需求数量</span>
                      <span class="stock-item">期望交付日期</span>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item v-for="item in purchaseApplyList">
                    <div class="stock-list">
                      <span class="stock-item">{{ item.purchaseApplyCode   }}</span>
                      <span class="stock-item">{{ item.purchaseNumber }}</span>
                      <span class="stock-item">{{ item.deliveryDate   }}</span>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          label="采购类型"
          prop="applicantType" v-if="checkList.includes('applicantType')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="期望交付日期"
          prop="deliveryDate" v-if="checkList.includes('deliveryDate')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <el-table-column
          label="关联项目名称"
          prop="projectName" v-if="checkList.includes('projectName')"
          :show-overflow-tooltip="false"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="点击进入项目详情"
              placement="top-start"
              v-if="row.projectName"
            >
              <span style="cursor: pointer;color: #409eff" @click="handleDetail(row)">{{
                row.projectName
              }}</span>
            </el-tooltip>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          label="申请日期"
          prop="applicantDate" v-if="checkList.includes('applicantDate')"
          :show-overflow-tooltip="true"
          width="160"
          sortable="custom"
        />
        <el-table-column
          label="状态"
          prop="purchaseTrackingStatusName" v-if="checkList.includes('purchaseTrackingStatusName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getRequestList"
      />
    </div>
    <RequestAdd
      ref="requestAddRef"
      v-show="requestAddShow"
      v-model:requestAddShow="requestAddShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />
    <OrderAdd
      ref="orderAddRef"
      v-show="orderAddShow"
      v-model:requestAddShow="orderAddShow"
      @refreshList="getRequestList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import RequestAdd from "../inquiry/requestadd";
import OrderAdd from "../order/requestadd";
import { getDictsApi } from "@/api/dict";
import { getRequestDetailListApi ,selectRelPurchaseApplyList} from "@/api/purchase/request";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
// 路由
const route = useRoute();
const router = useRouter();
// 搜索参数
const params = reactive({
  applicantType: null, // 请购类型
  manufactureName: "", // 生产厂商
  materialCode: "", // 物料编号
  materialName: "", // 物料名称
  nickName: "", // 申请人
  projectName: "", // 项目名称
  purchaseApplyCode: "", // 请购编号
  purchaseTrackingStatus: null, // 请购跟踪状态
  supplierName: "", // 供应商名称
  pageNum: 1,
  pageSize: 50,
  sortField: "",
    sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 客户列表
const requestList = ref([]);
// 状态列表
const checkOptions = ref([]);
// 采购类型列表
const typeList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const requestAddRef = ref(null);
// 客户新增组件显隐
const requestAddShow = ref(false);
// 操作类型
const pageType = ref("");
// 采购订单新增组件显隐
const orderAddShow = ref(false);
// 采购订单新增组件引用
const orderAddRef = ref(null);
// 表格选择
const multipleSelection = ref([]);
//库存下面的带计划请购单列表
const purchaseApplyList = ref([]);
const checkList = ref([
  "purchaseApplyCode",
  "materialCode",
  "materialName",
  "factoryCode",
  "technologyParameter",
  "materialUnitName",
  "purchasePrice",
  "historicalPrice",
  "distributorName",
  "manufacturer",
  "purchaseNumber",
  "stock",
  "applicantType",
  "deliveryDate",
  "projectName",
  "applicantDate",
  "purchaseTrackingStatusName",
]);

/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType:14,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 14,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
 const handleRefresh = () => {
  Object.assign(params, {
    applicantType: null, // 请购类型
  manufactureName: "", // 生产厂商
  materialCode: "", // 物料编号
  materialName: "", // 物料名称
  nickName: "", // 申请人
  projectName: "", // 项目名称
  purchaseApplyCode: "", // 请购编号
  purchaseTrackingStatus: null, // 请购跟踪状态
  supplierName: "", // 供应商名称
  sortField: "",
    sortOrder: "",
    pageNum: 1,
    pageSize: 50,
  });
  getRequestList()
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
 const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getRequestList();
};


/**
 * @description: 获取客户列表
 */
const getRequestList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    const res = await getRequestDetailListApi({ pageNum, pageSize }, params);
    requestList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/* 请购明细已计划的不能再次被选中 */
const checkSelectable = (row) => {
  if (row.purchaseTrackingStatusName == "待计划") {
    return true;
  } else {
    return false;
  }
};

/**
 * @description: 处理表格选中
 */
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

/**
 * @description: 生成询比价
 */
const handleAddInquiry = () => {
  if (!multipleSelection.value.length) {
    return ElMessage.info("请选择请购明细");
  }
  requestAddShow.value = true;
  requestAddRef.value.handleRequestDetailChoose(multipleSelection.value);
  pageType.value = "add";
};

/**
 * @description: 生成采购订单
 */
const handleAddOrder = () => {
  if (!multipleSelection.value.length) {
    return ElMessage.info("请选择请购明细");
  }
  orderAddShow.value = true;
  orderAddRef.value.handleRequestDetailChoose(multipleSelection.value);
  pageType.value = "add";
};
/**
 * @description: 处理导出
 */
 const handleExport = async () => {
  // 日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  let month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，因此要加1
  if (month < 10) {
    month = "0" + month;
  }
  const day = currentDate.getDate();
  let date = year + "" + month + "" + day;
  // 随机数
  let randomNum = Math.floor(Math.random() * (999 - 100 + 1) + 100);
  // 用户昵称
  let userName = userStore.name;
  // 文件名
  let fileNmae = date + userName + randomNum;
  let { pageNum, pageSize } = params;
  console.log('params')
  console.log(params)
    /* 导出 */
    proxy.download(
      `/system/apply/selectMaterialDetailExport?pageNum=${pageNum}&pageSize=${pageSize}`,
      params,
      `请购明细${fileNmae}.xlsx`,
      null,
      1
    );
};
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 状态
  await getDictsApi("erp_purchase_tracking_status").then((res) => {
    if (res.code === 200) {
      checkOptions.value = res.data;
    }
  });

  // 类型
  await getDictsApi("erp_applicant_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
}

/* 点击行内库存数据 */
const handleStock=async(row)=>{
  let params={
    materialCode:row.materialCode,
  }
  await selectRelPurchaseApplyList(params).then((res) => {
    if (res.code === 200) {
      purchaseApplyList.value=res.data
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

/* 跳转项目详情 */
const handleDetail = (row) => {
  const { href } = router.resolve({
        path: `/sales/project`,
        query:{projectId:row.projectId}
      });
      window.open(href, '_blank');
  // window.open(`/sales/project?projectId=${row.projectId}`, '_blank');
};

onMounted(() => {
  getTableHeader();
  getDicts();
  getRequestList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
}
.el-dropdown .el-dropdown-link {
  color: #606266 !important;
}
.stock-list{
  display: flex;
  align-items: center;
}
.stock-item{
  display: inline-block;
  width: 100px;
  text-align: center;
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
</style>
